package com.service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.client.RecordCreateService;
import com.db.ColumnInfoBean;
import com.db.connection.DBCPConnectionManager2;
import com.db.connection.DBCPPostgresManager;
import com.db.domain.Communication;
import com.excel.read.Config;
import com.excel.read.DBTable;
import com.operation.OperationMap;
import com.operation.POXML;
import com.xml.GetRecordExtract;
import com.xml.Record;

/**
 * 根据本地的记录复制远程节点所需的记录 一个本地记录要被复制到所有其他节点
 * 
 * @author mike
 * 
 */
public class CCServiceClient implements Runnable {

	//线程运行的时间间隔，当遇到异常时时间间隔调大，并给以警告，正常时调小
	public static final int timeNormal  = 1000;
	public static final int timeERR  = 20000;	
	public static int dltTime = timeNormal;
	public static List<Long> list = new ArrayList<Long>();

	public List<Communication> getRequest(long storeId) throws Exception {
		List<Communication> list = null;
		CCService aCCService = SyncServiceFactory.getCCService();
		//取得其他店对本店的请求
		list = aCCService.getRequest(storeId);
		for(Communication aCommunication : list) {
			String request = aCommunication.request;
			String type = aCommunication.getType();
			//请求类型为：取本店记录
			if(type.equalsIgnoreCase("get")) {
				
				OperationMap aOperationMap = (new GetRecordExtract()).extractOperationMap(request, storeId);
				String tableName = aOperationMap.opTableName;
				Record record = aOperationMap.record;
				DBTable dbTable = Config.allTable.get(tableName.toLowerCase());
				ColumnInfoBean cInfo = dbTable.getPk();
				Object obj = record.fieldMap.get(cInfo.getName().toLowerCase()); 
				com.db.domain.Record aRecord = getRecord(tableName, Long.parseLong(obj.toString()));
				//设置响应
				aCommunication.setResponse(aRecord.content);
			}
			
		}
		//发送响应
		aCCService.sendResponse(list);
		
		
		
		
		return list;
	}
	
	
	
	public List<Communication> requestAndGetresponse(long storeId) throws Exception {
		List<Communication> list = null;
		CCService aCCService = SyncServiceFactory.getCCService();
		//取得其他店对本店的请求
		
		
		
		
		
		return list;
	}
	
/////////////////////////////////////////////////////////////////////////
	/**
	 * 取得某个表的记录,放在缓存中，只要有服务端请求，就给它
	 * 用于客户端不存在外键时到服务端取数据
	 * @return
	 * @throws SQLException
	 */
	private static com.db.domain.Record getRecord(String tableName, Long id) throws SQLException
	{
		com.db.domain.Record aRecord = null;
		Connection conn = null;
		
		
		// 执行SQL语句
		String sql = "select * from "+tableName+"where id = ?";
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try
		{
			conn = DBCPPostgresManager.getConnection();
			pstmt = conn.prepareStatement(sql);	
			pstmt.setLong(1, id);
			rs = pstmt.executeQuery();
			//取得所有字段，组装成Record
			if (rs.next()) {
				aRecord = new com.db.domain.Record();
				DBTable dbTable = Config.allTable.get(tableName.toLowerCase());
				String xml = POXML.getXML(dbTable, rs);
				aRecord.setStoreId(0L);				
				aRecord.setContent(xml);
				SimpleDateFormat sft = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
				aRecord.setCreated(sft.format(new Date()));				
				//aRecord.setOperation("insert");
			}
		}
		catch (Exception e)
		{
			
		}
		finally
		{
			DBCPConnectionManager2.close(conn, pstmt, rs);	
		}
		return aRecord;
		
	}	//	fillCombos
	
	
	public void run() {
		try {
			while (true) {
				//取请求
				try {
					 List<Communication> aList = getRequest(1L);
					 
				} catch (Exception e) {					
					e.printStackTrace();
				}
				//发响应
				
				Thread.currentThread().sleep(dltTime);
				//System.out.println("next...");
			}
		} catch (InterruptedException e) {			
			e.printStackTrace();
		}

	}
}
